package com.lin.fengxiu.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lin.fengxiu.exception.http.ServerErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @ClassName GenericAndJson
 * @Description TODO
 * @Author wushaopei
 * @Date 2021/3/16 6:45
 * @Version 1.0
 */
@Component
public class GenericAndJson {

    private static ObjectMapper mapper;

    @Autowired
    public void setMapper(ObjectMapper mapper){
        GenericAndJson.mapper = mapper;
    }

    /**
     * @Description 序列化
     * @param o
     * @param <T>
     * @return 返回值为泛型对象
     */
    public static <T> String objectToJson(T o){
        try{
            return GenericAndJson.mapper.writeValueAsString(o);
        }catch (Exception e){
            e.printStackTrace();
            throw new ServerErrorException(9999);
        }
    }

    public static <T> T jsonToObject(String s, TypeReference<T> tr){
        if(s == null){
            return null;
        }
        try{
            // 根据传入类型的元类来反序列化
//            将原类给带入进来，将o返回回去
            T o = GenericAndJson.mapper.readValue(s, tr);
            return o;
        }catch (JsonProcessingException e){
            e.printStackTrace();
            throw new ServerErrorException(9999);
        }
    }
//
//    public static <T> List<T> jsonToList(String s){
//        if(s == null){
//            return null;
//        }
//        try{
//            List<T> list = GenericAndJson.mapper.readValue(s, new TypeReference<List<T>>() {
//            });
//            return list;
//        }catch (JsonProcessingException e){
//            e.printStackTrace();
//            throw new ServerErrorException(9999);
//        }
//
//    }

    // List<T> 泛型 T
    public static <T> T jsonToList(String s,TypeReference<T> tr){
        if(s == null){
            return null;
        }
        try{
            T list = GenericAndJson.mapper.readValue(s, tr);
            return list;
        }catch (JsonProcessingException e){
            e.printStackTrace();
            throw new ServerErrorException(9999);
        }
    }
}
